//
//  File.swift
//  RoNetVideo
//
//  Created by rolodestar on 2025/7/4.
//

import Foundation
import SwiftUI

@available(macOS 10.15.0, iOS 13.0.0, *)
class SearchHotStore{
//    static let shared = SearchHotStore()
       private let baseURL = "https://api.bilibili.com/x/web-interface/ranking/v2"
       static private let session = URLSession.shared
       
       static func fetchRankingData(rid: Int = 1, type: String = "hot") async  -> [VideoItem] {
           let baseURL = "https://api.bilibili.com/x/web-interface/ranking/v2"
           var components = URLComponents(string: baseURL)
           components?.queryItems = [
               URLQueryItem(name: "rid", value: "\(rid)"),
               URLQueryItem(name: "type", value: type),
               URLQueryItem(name: "jsonp", value: "jsonp")
           ]
//           
           guard let url = components?.url else {
//               throw ResponseError.invalidURL
               return []
           }
//           
           var request = URLRequest(url: url)
           request.httpMethod = "GET"
           request.setValue("Mozilla/5.0.BiliTV/1.7.2", forHTTPHeaderField: "User-Agent")
           request.setValue("https://www.bilibili.com/", forHTTPHeaderField: "Referer")
           request.addValue("application/json", forHTTPHeaderField: "Accept")
           request.timeoutInterval = 30
           
           print("请求URL: \(request.url?.absoluteString ?? "未知URL")")
           print("请求头: \(request.allHTTPHeaderFields ?? [:])")
           
           do {
               print("准备发起请求...")
               print("发起请求...")
               let (data, response) = try await session.data(for: request)
               print("请求完成，开始处理响应...")
               
               guard let httpResponse = response as? HTTPURLResponse else {
                   throw ResponseError.invalidData
               }
               print("响应状态码: \(httpResponse.statusCode)")
               print("响应头: \(httpResponse.allHeaderFields)")
               print("响应数据大小: \(data.count) 字节")
               let responseString = String(data: data, encoding: .utf8) ?? "无法解析响应数据"
               print("原始响应数据: \(responseString.prefix(200))")
               
               let decoder = JSONDecoder()
               decoder.keyDecodingStrategy = .convertFromSnakeCase
               let apiResponse = try decoder.decode(SearchHotResponse.self, from: data)
               guard apiResponse.code == 0, let data = apiResponse.data else {
                   throw ResponseError.apiError(code: apiResponse.code, message: apiResponse.message)
               }
               print("JSON解码成功，共解析 \(data.list.count) 条数据")
               return data.list
           } catch {
               if error is URLError {
                   print("ResponseError.networkError(urlError)")
                   return []
//                   throw ResponseError.networkError(urlError)
               } else if error is DecodingError {
                   print("ResponseError.decodingError(error)")
                   return []
//                   throw ResponseError.decodingError(error)
               } else {
                   print("ResponseError.invalidData")
                   return []
//                   throw ResponseError.invalidData
               }
           }
       }
    static let requestUrl = URL(string: "https://api.bilibili.com/x/web-interface/ranking/v2?rid=0&type=all")!
    
    static func requestSearchHot() async -> SearchHotResponse?{
        do{
            let session = URLSession.shared
            let (responseData,_) = try await session.data(from: requestUrl)
            let response =  SearchHotResponse.createModel(from: responseData)
            return response
        }catch let error as DecodingError {
            switch error {
            case .keyNotFound(let key, let context):
                print("⚠️ 缺失关键字段: \(key.stringValue)")
                print("解析路径: \(context.codingPath.map { $0.stringValue }.joined(separator: " → "))")
            case .typeMismatch(let type, let context):
                print("🚨 类型不匹配: 预期 \(type) - 路径: \(context.codingPath)")
            default:
                print("⚠️ 解码错误: \(error)")
                
            }
            return nil
        } catch {
            print("❗ 未知错误: \(error)")
            return nil
        }
        
    }
    static func requestSearchHotDebug(data: Data) async -> SearchHotResponse?{
        
            
            let response =  SearchHotResponse.createModel(from: data)
            return response
        
        
    }
}
